package dao;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {

	// 定义连接信息
	private static String driver;
	private static String url;
	private static String username;
	private static String password;

	// 静态代码块
	static {
		init();
	}

	public static void init() {
		try {
			Properties properties = new Properties();
			// 将database.properties读取到输入流中
			InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("database.properties");
			// properties对象通过load方法去输入流中拿数据
			properties.load(is);

			// 取值
			driver = properties.getProperty("driver");
			url = properties.getProperty("url");
			username = properties.getProperty("username");
			password = properties.getProperty("password");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 加载驱动、获取连接
	 * 
	 * @return
	 */
	public Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 释放资源
	 * 
	 * @param conn
	 * @param stmt
	 * @param rs
	 */
	public void closeAll(Connection conn, Statement stmt, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
